---------------------------------------
-- godWarDB = {
-- 	rank2Uuid = {},
-- 	uuid2Roles = {},
-- 	match2Fight = {},
-- 	jingCai = {},
-- 	isSendReward = nil, --发放奖励
-- 	saveCombatState = nil, --已保存x轮的战斗数据镜像
-- 	time = os.time(), --本期活动初始化时间
-- 	lastTopThree = nil, --上一期前三名的信息
-- }
-- rank2Uuid = {}, -- rank2Uuid[rank] = uuid(包括真人与npc)
-- uuid2Roles = {}, -- uuid2Roles[uuid] = roleData(包括真人与npc)
-- match2Fight = {}, --各阶段比赛分组 match2Fight[state][fenzuID][paisIndex]{atkUuid,defUuid,winUuid,vestID} 
	-- 选拔赛 fenzuID只有1
	-- 32强 16强 8强 fenzuID最大4
	-- 4强 决赛 fenzuID只有1
-- 	match2Fight[选拔赛1][1][双方队伍1] 
-- 	match2Fight[32强][1][双方队伍1]
-- 	match2Fight[32强][2][双方队伍1]

-- jingCai = {}, --竞猜队伍 jingCai[state]{fenzuID,pairsIndex,yazhu{atkuuid=nil,defuuid=nil}}
-- 	jingCai[选拔赛1]{fenzuID=分组1,pairIndex=双方队伍1,yazhu{atkuuid=1,defuuid=nil}}
---------------------------------------

local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local Util = require("common.Util")
local ObjHuman = require("core.ObjHuman")
local CombatVideo = require("combat.CombatVideo")
local CreateRole = require("role.CreateRole")
local JjcGodWarExcel = require("excel.jjcGodWar")
local RoleDBLogic = require("role.RoleDBLogic")
local JjcDB = require("jjc.JjcDB")
local JjcGodWarLogic = require("jjcGodWar.JjcGodWarLogic")
local RoleLogic = require("role.RoleLogic")
local CombatLogic = require("combat.CombatLogic")
local CombatDefine = require("combat.CombatDefine")
local CombatPosLogic = require("combat.CombatPosLogic")
local WarReportLogic = require("warReport.WarReportLogic")

GODWAR_FIGHT_MAX = 128 --竞技场积分排名前128名参加

GODWAR_FENZU_32 = 32 --选拔赛，竞技场前32名不会相遇

local DBUpdate = { _id = nil }
local DBUpdateField = {} --更新域九 零 一 起玩 www.9 01  7 5.com 
local QueryByVestID = {_id = nil}

GODWAR_DB = GODWAR_DB or {}

function initAfterStart()
	if _G.is_middle == true then return end
	LuaMongo.find(DB.db_jjcGodWar)
	local godWarDB = {}
	if not LuaMongo.next(godWarDB) then
		return
	end
	GODWAR_DB = godWarDB
end

-- 活动开始时 初始化
function initGodWar()
	local db = {
	rank2Uuid = {}, -- rank2Uuid[rank] = uuid
	uuid2Roles = {}, -- uuid2Roles[uuid] = data
	match2Fight = {[0]=0}, --各阶段比赛分组 match2Fight[state][fenzuID][paisIndex] match2Fight[选拔赛1][分组1（abcd）][双方队伍1]{atkUuid,defUuid,winUuid,vestID}
	jingCai = {[0]=0}, --竞猜队伍 jingCai[state][fenzuID,pairsIndex,yazhu] jingCai[选拔赛1][fenzuID=分组1,pairIndex=1,yazhu{atkuuid=nil,defuuid=nil}]
	isSendReward = nil, --发放奖励
	saveCombatState = nil, --已保存x轮的战斗数据镜像
	time = os.time(), --本期活动初始化时间
	lastTopThree = nil, --上一期前三名的信息
	uuid2Yazhu = nil, --玩家押注信息 uuid2Yazhu[uuid]{jingCai[state],jingCaiBi}
	pointCheckState = nil, --已结算x轮积分
	jingCaiCalcState = nil, --竞猜x轮结算
	danMuList = {},   -- 弹幕
}
	
	-- 清理多余的战斗数据记录
	LuaMongo.remove(DB.db_jjcGodWar_record)

	LuaMongo.find(DB.db_jjcGodWar)
	local godWarDB = {}
	if not LuaMongo.next(godWarDB) then
		LuaMongo.insert(DB.db_jjcGodWar, db)
		godWarDB = db
	end

	local rank2Uuid = godWarDB.rank2Uuid
	local uuid2Roles = godWarDB.uuid2Roles

	godWarDB = db

	if rank2Uuid and #rank2Uuid >= 1 then
		godWarDB.lastTopThree = {}
		for rank=1,3 do
			local uuid = rank2Uuid[rank]
			local roleData = uuid2Roles[uuid]
			if roleData then
				godWarDB.lastTopThree[rank] = roleData
			end
		end
	end

	local conf = JjcGodWarExcel.define[1]
	local jjcRank2Data = JjcDB.RANK_2_JJCDATA
	for rank=1,GODWAR_FIGHT_MAX do
		local roleData = nil
		local jjcData = jjcRank2Data[rank]
		local uuid = jjcData._id
		if not JjcDB.isNpc(jjcData) then
			local fakeDB = RoleDBLogic.getDb(uuid)
			local fakeHuman = {}
			fakeHuman.db = fakeDB
			local combatHero = CombatPosLogic.getCombatHeros(fakeHuman, CombatDefine.COMBAT_TYPE4) 
			if CombatLogic.isCombatHeroEmpty(combatHero) then
				CombatPosLogic.copyCombatHeros(fakeHuman, CombatDefine.COMBAT_TYPE1, CombatDefine.COMBAT_TYPE4)
				ObjHuman.save(fakeHuman)
			end
			local objList, helpList, rolebase, formation = CombatLogic.getHumanObjList(fakeHuman, CombatDefine.COMBAT_TYPE4)

			roleData = {}
			roleData.objList = Util.copyTable(objList)
			roleData.helpList = Util.copyTable(helpList)
			roleData.rolebase = Util.copyTable(rolebase)
			roleData.formation = formation
		else
			roleData = Util.copyTable(jjcData)
		end
		
		if roleData then
			godWarDB.rank2Uuid[rank] = uuid
			roleData.uuid = uuid			
			roleData.point = math.floor(jjcData.point * conf.jifenXuanBaGap)
			roleData.beiMoBai = 0
			roleData.sendFinalTip = nil --结算面板
			roleData.combatResultList = nil --胜利列表
			roleData.chenghao = nil --称号
			-- if not JjcDB.isNpc(jjcData) then
			-- 	require("common.Util").printTable(roleData)
			-- end
			godWarDB.uuid2Roles[uuid] = roleData 
		end
	end
	--本期活动开始 先分组选拔赛
	godWarXuanBaFenZu(godWarDB)

	updateGodWarDB(godWarDB)
	--WarReportLogic.removeByType(WarReportLogic.WAR_REPORT_2)
	return godWarDB
end

-- 获取godWarDB
function getGodWarDB()
	return GODWAR_DB
end

-- 获取个人信息 通过uuid
function getGodWarDataByUuid(uuid)
	local uuid2Roles = getGodWarUuid2Roles()
	if not uuid2Roles then return end
	
	return uuid2Roles[uuid]
end

function getRankByUuid(uuid)
	local rank2Uuid = getGodWarRank2Uuid()
	if not rank2Uuid then return end

	for i=1,#rank2Uuid do
		if uuid == rank2Uuid[i] then
			return i
		end
	end
end

function getGodWarRank2Uuid()
	return GODWAR_DB.rank2Uuid
end

function getGodWarUuid2Roles()
	return GODWAR_DB.uuid2Roles
end

function getGodWarMatch2Fight()
	return GODWAR_DB.match2Fight
end

function getGodWarLastTopThree()
	return GODWAR_DB.lastTopThree
end

function getGodWarUuid2Yazhu()
	return GODWAR_DB.uuid2Yazhu
end

function getGodWarDanMuList()
	return GODWAR_DB.danMuList
end

-- 获取个人信息 通过排名
function getGodWarDataByRank(rank)
	if not GODWAR_DB.rank2Uuid or 
		not GODWAR_DB.uuid2Roles then return end

	local targetUuid = GODWAR_DB.rank2Uuid[rank]
	return GODWAR_DB.uuid2Roles[targetUuid]
end

--更新DB信息
function updateGodWarDB(godWarDB)
	DBUpdate._id = godWarDB._id

	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, godWarDB)

	GODWAR_DB = godWarDB
end

--更新db中排名信息
function updateGodWarRank(rank2Uuid)
	DBUpdate._id = GODWAR_DB._id

	DBUpdateField = {["$set"]={["rank2Uuid"]=rank2Uuid}}
	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, DBUpdateField)

	GODWAR_DB.rank2Uuid = rank2Uuid
end


--更新db中玩家信息通过uuid
function updateGodWarRoleDataByUuid(roleData,uuid)
	DBUpdate._id = GODWAR_DB._id
	DBUpdateField = {["$set"]={["uuid2Roles."..uuid]=roleData}}

	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, DBUpdateField)

	GODWAR_DB.uuid2Roles[uuid] = roleData
end

--更新db中玩家信息
function updateGodWarRoleData(uuid2Roles)
	DBUpdate._id = GODWAR_DB._id

	DBUpdateField = {["$set"]={["uuid2Roles"]=uuid2Roles}}
	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, DBUpdateField)

	GODWAR_DB.uuid2Roles = uuid2Roles
end

--更新db中玩家竞猜信息通过uuid
function updateGodWarYaZhuByUuid(yazhuData,uuid)
	DBUpdate._id = GODWAR_DB._id
	DBUpdateField = {["$set"]={["uuid2Yazhu."..uuid]=yazhuData}}

	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, DBUpdateField)

	GODWAR_DB.uuid2Yazhu[uuid] = yazhuData
end

--更新db中玩家竞猜信息
function updateGodWarYaZhu(uuid2Yazhu)
	DBUpdate._id = GODWAR_DB._id

	DBUpdateField = {["$set"]={["uuid2Yazhu"]=uuid2Yazhu}}
	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, DBUpdateField)

	GODWAR_DB.uuid2Yazhu = uuid2Yazhu
end

function updateJingCaiData(state,jingCaiData)
	DBUpdate._id = GODWAR_DB._id

	DBUpdateField = {["$set"]={["jingCai."..state]=jingCaiData}}
	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, DBUpdateField)

	GODWAR_DB.jingCai[state] = jingCaiData
end

--更新db中押注信息
function jingCaiYaUpdate(targetUuid)
	local state,round,leftTime = JjcGodWarLogic.getNowGodWarState()
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return end

	local jingCaiData = getGodWarJingCaiData(state)
	if not jingCaiData then return end

	jingCaiData.yaZhu = jingCaiData.yaZhu or {}
	if not jingCaiData.yaZhu[targetUuid] then
		jingCaiData.yaZhu[targetUuid] = 1
	end

	updateJingCaiData(state,jingCaiData)
end

--更新个人押注记录
function updateYaZhuByUuid(uuid,yaUuid,yaZhuCnt)
	local state,round,leftTime = JjcGodWarLogic.getNowGodWarState()
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return end

	local uuid2Yazhu = getYaZhuDataByUuid(uuid)
	if not uuid2Yazhu then return end

	local yazhuData = {
	yaUuid = yaUuid,
	yaZhuCnt = yaZhuCnt,
}	
	uuid2Yazhu.jingCai = uuid2Yazhu.jingCai or {}
	uuid2Yazhu.jingCai[state] = yazhuData

	updateGodWarYaZhuByUuid(uuid2Yazhu,uuid)
end

-- 更新32强赛分组
function updateMatch2Fight(match2FightData,state)
	--require("common.Util").printTable(match2FightData)
	DBUpdate._id = GODWAR_DB._id

	DBUpdateField = {["$set"]={["match2Fight."..state]=match2FightData}}
	LuaMongo.update(DB.db_jjcGodWar, DBUpdate, DBUpdateField)

	GODWAR_DB.match2Fight[state] = match2FightData
end

function updateDanMu(uuid, desc)
	local list = getGodWarDanMuList()
	if not list then
		GODWAR_DB.danMuList = {}
		list = getGodWarDanMuList()
	end
	list[#list + 1] = {}
	list[#list].uuid = uuid
	list[#list].desc = desc


	if #list > 150 then
		for i = 1, 150 do
			list[i] = list[i + 1]
		end
	end
end

local function checkAtkGroupID(checkGroup,atkGroupID)
	for atk,def in pairs(checkGroup) do
		if def == atkGroupID then
			return 
		end
	end

	return true
end

function makeRankGroup(group,min,max)
	local randGroup = {}
	for rank=min,max do
		local index = #randGroup + 1
		randGroup[index] = rank
	end

	for i=min,max do
		local randIndex = math.random(1,#randGroup)
		local randRank = randGroup[randIndex]
		group[#group+1] = randRank
		randGroup[randIndex],randGroup[#randGroup] = randGroup[#randGroup],randGroup[randIndex]
		randGroup[#randGroup] = nil
	end
end

--选拔赛分组初始化
--竞技场前32强选拔赛不会相遇
--在6轮选拔赛中只会相遇相同对手1次
function godWarXuanBaFenZu(godWarDB)
	local state,round,leftTime = JjcGodWarLogic.getNowGodWarState()
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return end
	if godWarDB.match2Fight[state] then return end

	local rank2Uuid = godWarDB.rank2Uuid
	
	--选拔赛
	if state >= JjcGodWarLogic.GODWAR_STATE_XUANBA1 
		and state <= JjcGodWarLogic.GODWAR_STATE_XUANBA6 then

		--竞技场前32强选拔赛不会相遇
		--相遇对手只有1次
		--128人分成4组，两两配对
		--第一轮（1，2）（3，4） 第二轮 （1，2）（3，4）反转
		local xuanbaList = {
			[1] = {2, 2, 3, 3, 4, 4},
		    [2] = {1, 1, 4, 4, 3, 3},
		    [3] = {4, 4, 1, 1, 2, 2},
		    [4] = {3, 3, 2, 2, 1, 1},
		}

		local randGroup = {}
		makeRankGroup(randGroup,1,32)
		makeRankGroup(randGroup,33,128)

		local n = 0
		local xuanbaGroup = {}
		for i=1,#xuanbaList do
			xuanbaGroup[i] = {}
			for j=1,#rank2Uuid / #xuanbaList do
				n = n + 1
				local rank = randGroup[n]
				xuanbaGroup[i][#xuanbaGroup[i] + 1] = rank
			end
		end

		for i=1,JjcGodWarLogic.GODWAR_STATE_XUANBA6 do
			local checkGroup = {}
			godWarDB.match2Fight[i] = {}
			godWarDB.match2Fight[i][1] = {}
			local pairsData = {}
			for j=1,#xuanbaList do
				atkGroupID = j
				defGroupID = xuanbaList[j][i]

				if checkAtkGroupID(checkGroup,atkGroupID) then
					checkGroup[atkGroupID] = defGroupID
					local groupAtk = xuanbaGroup[j]
					local groupDef = xuanbaGroup[defGroupID]

					if i % 2 == 1 then --第一次
						for k=1,#groupAtk do
							local atkUuid = rank2Uuid[groupAtk[k]]
							local defUuid = rank2Uuid[groupDef[k]]
							local index = #godWarDB.match2Fight[i][1] + 1
							godWarDB.match2Fight[i][1][index] = {}
							godWarDB.match2Fight[i][1][index].atkUuid = atkUuid
							godWarDB.match2Fight[i][1][index].defUuid = defUuid
							godWarDB.match2Fight[i][1][index].winUuid = nil
							godWarDB.match2Fight[i][1][index].vestID = nil
							godWarDB.match2Fight[i][1][index].atkRank = groupAtk[k] -- 测试
							godWarDB.match2Fight[i][1][index].defRank = groupDef[k] -- 测试
						end
					else --第二次
						for k=1,#groupAtk do
							local atkUuid = rank2Uuid[groupAtk[k]]
							local defUuid = rank2Uuid[groupDef[#groupAtk - k + 1]]
							local index = #godWarDB.match2Fight[i][1] + 1
							godWarDB.match2Fight[i][1][index] = {}
							godWarDB.match2Fight[i][1][index].atkUuid = atkUuid
							godWarDB.match2Fight[i][1][index].defUuid = defUuid
							godWarDB.match2Fight[i][1][index].winUuid = nil
							godWarDB.match2Fight[i][1][index].vestID = nil
							godWarDB.match2Fight[i][1][index].atkRank = groupAtk[k] -- 测试
							godWarDB.match2Fight[i][1][index].defRank = groupDef[#groupAtk - k + 1] -- 测试
						end
					end
				end
			end
		end
	end

	--require("common.Util").printTable(godWarDB.match2Fight)
end

-- 通过state获得排位分组
function getMatch2Fight(state)
	if not GODWAR_DB.match2Fight then return end

	return GODWAR_DB.match2Fight[state]
end

--排位赛分组
--32强-决斗，比较特殊 32个玩家分成4组abcd，每组8个人
--32强赛每组决出4个胜利者一共16人
--16强赛每组决出2个胜利者一共8人
--8强赛每组决出1个胜利者一共4人
--4强赛剩余四个人形成一个小组，两两配对，决出2个胜利者
--决赛剩余两人，争夺冠亚军，季军由4强中落选两人积分最高或统计分战斗力最高者担任
function paiweiFenzu(state)
	if state >= JjcGodWarLogic.GODWAR_STATE_END then return end
	if getMatch2Fight(state) then return end

	local rank2Uuid = getGodWarRank2Uuid()
	if not rank2Uuid then return end

	local match2FightData = nil
	if state == JjcGodWarLogic.GODWAR_STATE_PAIWEI32 then --32强
		local group = {}
		for i=1,4 do
			group[i] = {}
			group[i][1] = rank2Uuid[i]
		end

		local n = 5
		for i=1,4 do
			for j=1,7 do
				group[i][#group[i]+1] = rank2Uuid[n]
				n = n + 1
			end
		end

		match2FightData = {}
		for i=1,4 do
			match2FightData[i] = {}
			local index = 1
			for j=1,4 do
				local atkUuid = group[i][index]
				local defUuid = group[i][index + 1]

				match2FightData[i][j] = {}
				match2FightData[i][j].atkUuid = atkUuid
				match2FightData[i][j].defUuid = defUuid
				match2FightData[i][j].winUuid = nil
				match2FightData[i][j].vestID = nil
				index = index + 2
			end
		end
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI16 then --16强
		local paiwei32Pairs = getMatch2Fight(JjcGodWarLogic.GODWAR_STATE_PAIWEI32)
		local group = {}
		for i=1,#paiwei32Pairs do
			group[i] = {}
			local fenzuData = paiwei32Pairs[i]
			for j=1,#fenzuData do
				local winUuid = fenzuData[j].winUuid
				if not winUuid then return end

				group[i][j] = winUuid
			end
		end

		match2FightData = {}
		for i=1,4 do
			match2FightData[i] = {}
			local index = 1
			for j=1,2 do
				local atkUuid = group[i][index]
				local defUuid= group[i][index + 1]

				match2FightData[i][j] = {}
				match2FightData[i][j].atkUuid = atkUuid
				match2FightData[i][j].defUuid = defUuid
				match2FightData[i][j].winUuid = nil
				match2FightData[i][j].vestID = nil
				
				index = index + 2
			end
		end
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI8 then --8强
		local paiwei16Pairs = getMatch2Fight(JjcGodWarLogic.GODWAR_STATE_PAIWEI16)
		local group = {}
		for i=1,#paiwei16Pairs do
			group[i] = {}
			local fenzuData = paiwei16Pairs[i]
			for j=1,#fenzuData do
				local winUuid = fenzuData[j].winUuid
				if not winUuid then return end

				group[i][j] = winUuid
			end
		end

		match2FightData = {}
		for i=1,4 do
			match2FightData[i] = {}
			local atkUuid = group[i][1]
			local defUuid= group[i][2]
			match2FightData[i][1] = {}
			match2FightData[i][1].atkUuid = atkUuid
			match2FightData[i][1].defUuid = defUuid
			match2FightData[i][1].winUuid = nil
			match2FightData[i][1].vestID = nil
		end
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI4 then --4强
		local paiwei8Pairs = getMatch2Fight(JjcGodWarLogic.GODWAR_STATE_PAIWEI8)
		local group = {}
		for i=1,#paiwei8Pairs do
			local fenzuData = paiwei8Pairs[i]
			local winUuid = fenzuData[1].winUuid
			if not winUuid then return end

			group[i] = winUuid
		end

		match2FightData = {}
		match2FightData[1] = {}

		local index = 1
		for i=1,2 do
			local atkUuid = group[index]
			local defUuid= group[index + 1]

			match2FightData[1][i] = {}
			match2FightData[1][i].atkUuid = atkUuid
			match2FightData[1][i].defUuid = defUuid
			match2FightData[1][i].winUuid = nil
			match2FightData[1][i].vestID = nil

			index = index + 2
		end
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI1 then --决赛
		local paiwei4Pairs = getMatch2Fight(JjcGodWarLogic.GODWAR_STATE_PAIWEI4)
		local group = {}
		for i=1,#paiwei4Pairs do
			local data = paiwei4Pairs[i]
			for j=1,#data do
				local winUuid = data[j].winUuid
				if not winUuid then return end

				group[j] = winUuid
			end
		end

		local atkUuid = group[1]
		local defUuid= group[2]
		--print("atkUuid,defUuid",atkUuid,defUuid)
		match2FightData = {}
		match2FightData[1] = {}
		match2FightData[1][1] = {}
		match2FightData[1][1].atkUuid = atkUuid
		match2FightData[1][1].defUuid = defUuid
		match2FightData[1][1].winUuid = nil
		match2FightData[1][1].vestID = nil
	end

	if match2FightData then
		updateMatch2Fight(match2FightData,state)
		--require("common.Util").printTable(match2FightData)
	end
end

-- 检查队伍数据，若无则按排名强制生成
function checkMatch(state)
	local rank2Uuid = getGodWarRank2Uuid()
	if not rank2Uuid then return end

	for i=JjcGodWarLogic.GODWAR_STATE_PAIWEI32,state do
		if not getMatch2Fight(i) then
			local match2FightData = nil
			local fenzuMax = nil
			local pairsMax = nil
			if i == JjcGodWarLogic.GODWAR_STATE_PAIWEI32 then
				paiweiFenzu(i)
			elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI16 then --16强
				fenzuMax = 4
				pairsMax = 2
			elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI8 then --8强
				fenzuMax = 4
				pairsMax = 1
			elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI4 then --4强
				fenzuMax = 1
				pairsMax = 2
			elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI1 then --决赛
				fenzuMax = 1
				pairsMax = 1
			end

			if fenzuMax and pairsMax then
				match2FightData = {}
				local pairsIndex = 1
				for fenzu=1,fenzuMax do
					for pairs=1,pairsMax do
						match2FightData[fenzu] = match2FightData[fenzu] or {}
						local index = #match2FightData[fenzu] + 1
						
						match2FightData[fenzu][index] = {}
						local atkUuid = rank2Uuid[pairsIndex]
						local defUuid = rank2Uuid[pairsIndex + 1]
						match2FightData[fenzu][index].atkUuid = atkUuid
						match2FightData[fenzu][index].defUuid = defUuid

						pairsIndex = pairsIndex + 2
					end
				end

				updateMatch2Fight(match2FightData,i)
			end
		end
	end
end

-- 获取战斗力
function getNowZhandouli(uuid)
	local roleData = getGodWarDataByUuid(uuid)
	--print("uuid,roleData",uuid,roleData)
	local zhandouli = 0
	if not JjcDB.isNpc(roleData) then
		local fakeHuman = {}
		fakeHuman.db = RoleDBLogic.getDb(uuid, RoleLogic.getCombatField())
		if not fakeHuman.db then
			fakeHuman.db = roleData
		end
		zhandouli = CombatPosLogic.getCombatHeroZDL(fakeHuman, CombatDefine.COMBAT_TYPE4)
	else
		zhandouli = roleData.zhandouli
	end
	return zhandouli
end

--获取当前的x强排位赛所有配对，纯数据读取，选择性分组
function getNowPaiWeiAll(state,fenzuID)
	local data = getMatch2Fight(state)
	if not data then return end
	--print("data,#data",data,#data)
	local group = {}
	if not fenzuID then
		for i=1,#data do
			local fenzuData = data[i]
			--print("#fenzuData",#fenzuData)
			for j=1,#fenzuData do
				local pairsData = fenzuData[j]
				--print("atkUuid",pairsData.atkUuid)
				group[#group + 1] = pairsData
			end
		end
	else
		for i=1,#data do
			if i == fenzuID then
				local fenzuData = data[i]
				--print("#fenzuData",#fenzuData)
				for j=1,#fenzuData do
					local pairsData = fenzuData[j]
					--print("atkUuid",pairsData.atkUuid)
					group[#group + 1] = pairsData
				end
			end
		end
	end

	return group
end

-- 通过state获得当前界面需要展示的所有的配对信息
function getNowPaiWeiFenzu(nowState,fenzuID)
	if not getMatch2Fight(nowState) then return end
	local group = nil
	if nowState <= JjcGodWarLogic.GODWAR_STATE_PAIWEI8 then --32,16,8 需要合并数据
		for state=JjcGodWarLogic.GODWAR_STATE_PAIWEI32,nowState do
			local data = getNowPaiWeiAll(state,fenzuID)
			if data then
				group = group or {}
				group[state] = data
			end
		end
	else
		for i=JjcGodWarLogic.GODWAR_STATE_PAIWEI4,nowState do
			local data = getNowPaiWeiAll(i,fenzuID)
			if data then
				group = group or {}
				group[i] = data
			end
		end
	end

	return group
end

--获取最小战斗力差
local function getZhandouLiMinPair(state)
	local match2Fight = getMatch2Fight(state)
	local min = nil
	local fenzuID = nil
	local index = nil
	for i=1,#match2Fight do
		local fenzuData = match2Fight[i]
		for j=1,#fenzuData do
			local atkUuid = fenzuData[j].atkUuid
			local defUuid = fenzuData[j].defUuid
			local atkZhandouli = getNowZhandouli(atkUuid)
			local defZhandouli = getNowZhandouli(defUuid)
			
			local cha = 0
			if atkZhandouli > defZhandouli then
				cha = atkZhandouli - defZhandouli
			else
				cha = defZhandouli - atkZhandouli
			end
			--print("i,j,atkZhandouli,defZhandouli,cha",i,j,atkZhandouli,defZhandouli,cha)
			if not min or cha < min then
				min = cha
				fenzuID = i
				index = j
			end
		end
	end
	--print("min,fenzuID,index",min,fenzuID,index)
	return fenzuID,index
end

--生成竞猜队伍
function godWarJingCaiPairs()
	local state,round,leftTime = JjcGodWarLogic.getNowGodWarState()
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return end
	
	if getGodWarJingCaiData(state) then return end

	local match2Fight = getMatch2Fight(state)
	if not match2Fight then return end

	if state > JjcGodWarLogic.GODWAR_STATE_PAIWEI32 then
		local jingPaiWeiData = getGodWarJingCaiData(state-1)
		if jingPaiWeiData then
			local fenzuID = jingPaiWeiData.fenzuID

			local jingPaiWei2Fight = getGodWarJingCaiPairs(state-1)
			local winUuid = jingPaiWei2Fight.winUuid
			if winUuid then
				if #match2Fight == 1 then
					fenzuID = 1
				end
				local fenzuData = match2Fight[fenzuID]
				--print("fenzuID,winUuid,fenzuData,state",fenzuID,winUuid,fenzuData,state)
				for i=1,#fenzuData do
					local pairsData = fenzuData[i]
					if pairsData.atkUuid == winUuid or pairsData.defUuid == winUuid then
						local jingCaiData = {}
						jingCaiData.fenzuID = fenzuID
						jingCaiData.pairsIndex = i
						jingCaiData.yaZhu = nil
						--print("==================state,winUuid",state,winUuid)
						updateJingCaiData(state,jingCaiData)
						return
					end
				end
			end
		end
	end

	local fenzuID,index = getZhandouLiMinPair(state)
	--print("fenzuID,index",fenzuID,index)
	if not fenzuID then return end
	local jingCaiData = {}
	--print("==================state,#fenzuData,atkUuid,defUuid",state,#fenzuData,atkUuid,defUuid)
	jingCaiData.fenzuID = fenzuID
	jingCaiData.pairsIndex = index
	jingCaiData.yaZhu = nil

	updateJingCaiData(state,jingCaiData)
end

--获取配对信息
function getGodWarPairsDataByUuid(targetUuid)
	local state,round,leftTime = JjcGodWarLogic.getNowGodWarState()
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT then return end --活动开始倒计时界面，不需要显示战斗

	local roleData = getGodWarDataByUuid(targetUuid)
	local rank = getRankByUuid(targetUuid)
	if not roleData then return end --没资格的，不需要显示战斗

	local match2Fight = nil
	local nowCombat = true
	local getMatch2FightState = nil
	if state == JjcGodWarLogic.GODWAR_STATE_END then
		if rank > 32 then --取选拔赛6战斗
			getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_XUANBA6
		elseif rank > 16 and rank <= 32 then --取排位赛32强战斗
			getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI32
		elseif rank > 8 and rank <= 16 then --取排位赛16强战斗
			getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI16
		elseif rank > 4 and rank <= 8 then --取排位赛8强战斗
			getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI8
		elseif rank > 2 and rank <= 4 then --取排位赛4强战斗
			getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI4
		elseif rank <= 2 then --取排位赛决赛战斗
			getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI1
		end

		nowCombat = false
	else
		--取当前战斗
		--排位赛时，显示玩家最终止步的战斗
		if rank > 32 then
			if state >= JjcGodWarLogic.GODWAR_STATE_PAIWEI32 then
				getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_XUANBA6
				nowCombat = false
			end
		elseif rank > 16 and rank <= 32 then
			if state >= JjcGodWarLogic.GODWAR_STATE_PAIWEI16 then
				getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI32
				nowCombat = false
			end
		elseif rank > 8 and rank <= 16 then
			if state >= JjcGodWarLogic.GODWAR_STATE_PAIWEI8 then
				getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI16
				nowCombat = false
			end
		elseif rank > 4 and rank <= 8 then
			if state >= JjcGodWarLogic.GODWAR_STATE_PAIWEI4 then
				getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI8
				nowCombat = false
			end
		elseif rank > 2 and rank <= 4 then
			if state >= JjcGodWarLogic.GODWAR_STATE_PAIWEI1 then
				getMatch2FightState = JjcGodWarLogic.GODWAR_STATE_PAIWEI4
				nowCombat = false
			end
		end
	end
	--print("rank,nowCombat",rank,nowCombat)
	if nowCombat then
		getMatch2FightState = state
	end

	if getMatch2FightState then
		match2Fight = getMatch2Fight(getMatch2FightState)
	end
	--print("getMatch2FightState,match2Fight",getMatch2FightState,match2Fight)
	if not match2Fight then return end
	--print("match2Fight",match2Fight)
	for i=1,#match2Fight do
		local fenzuData = match2Fight[i]
		for j=1,#fenzuData do
			local pairsData = fenzuData[j]
			if pairsData.atkUuid == targetUuid
				or pairsData.defUuid == targetUuid then
				return pairsData,nowCombat,getMatch2FightState
			end
		end
	end
end

--获取当前竞猜信息
function getGodWarJingCaiData(state)
	if not GODWAR_DB.jingCai then return end
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return end
	
	return GODWAR_DB.jingCai[state]
end

--获取当前竞猜队伍信息
function getGodWarJingCaiPairs(state)
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return end

	local data = getGodWarJingCaiData(state)
	if not data then return end

	local fenzuID = data.fenzuID
	local pairsIndex = data.pairsIndex

	local match2Fight = getMatch2Fight(state)
	if not match2Fight then return end
	--print("fenzuID,pairsIndex",fenzuID,pairsIndex)
	return match2Fight[fenzuID][pairsIndex]
end

--获取当前竞猜队伍赔率 仅展示作用
function getJingcaiPei(state)
	local conf = JjcGodWarExcel.jingCai[1]
	local jingCaiData = getGodWarJingCaiData(state)
	if not jingCaiData or not jingCaiData.yaZhu then
		return conf.jingcaiShowPei1,conf.jingcaiShowPei1
	end

	local jingCaiPairs = getGodWarJingCaiPairs(state)
	local atkUuid = jingCaiPairs.atkUuid
	local defUuid = jingCaiPairs.defUuid

	local atkYaZhu = jingCaiData.yaZhu[atkUuid]
	local defYaZhu = jingCaiData.yaZhu[defUuid]
	if atkYaZhu and defYaZhu then
		return conf.jingcaiShowPei2,conf.jingcaiShowPei2
	elseif not atkYaZhu and defYaZhu then
		return conf.jingcaiShowPei1,conf.jingcaiShowPei2
	elseif atkUuid and not defYaZhu then
		return conf.jingcaiShowPei2,conf.jingcaiShowPei1
	end
end

function getYaZhuDataByUuid(uuid)
	local uuid2Yazhu = getGodWarUuid2Yazhu()
	if not uuid2Yazhu then return end

	return uuid2Yazhu[uuid]
end

--获取个人所有押注记录
function getJingCaiYaZhu(uuid)
	local uuid2Yazhu = getGodWarUuid2Yazhu()
	if not uuid2Yazhu or not uuid2Yazhu[uuid] then return end

	return uuid2Yazhu[uuid].jingCai
end

--通过阶段获取押注记录
function getJingCaiYaZhuByState(uuid,state)
	local yazhuData = getJingCaiYaZhu(uuid)
	if not yazhuData then return end

	return yazhuData[state]
end

--获取当前需要生成战斗数据的2个队伍
function getNowNeedCombat(state)
	local paiweiMatch = getMatch2Fight(state)
	if not paiweiMatch then return end

	local group = nil
	for i=1,#paiweiMatch do
		for j=1,#paiweiMatch[i] do
			local pairsData = paiweiMatch[i][j]
			if not pairsData.winUuid then
				group = group or {}
				local index = #group + 1
				group[index] = {}
				group[index].atkUuid = pairsData.atkUuid
				group[index].defUuid = pairsData.defUuid
				group[index].fenzuID = i
				group[index].pairsIndex = j
				
				if state == JjcGodWarLogic.GODWAR_STATE_PAIWEI1 then
					return paiweiMatch,group
				end

				if #group == 3 then
					return paiweiMatch,group
				end
			end
		end
	end

	if group and #group < 3 then
		return paiweiMatch,group
	end
end

local function getSaveZhandouli(uuid)
	local roleData = getGodWarDataByUuid(uuid)
	if not roleData then return 0 end
	--print("uuid,roleData",uuid,roleData)
	local zhandouli = 0
	if not JjcDB.isNpc(roleData) then
		zhandouli = roleData.rolebase.zhandouli
	else
		zhandouli = roleData.zhandouli
	end

	return zhandouli
end

--积分刷新排行榜
local function cmpJiFenRank(auuid, buuid)
	local uuid2Roles = getGodWarUuid2Roles()
	local aRoleData = uuid2Roles[auuid]
	local bRoleData = uuid2Roles[buuid]
	if aRoleData.point ~= bRoleData.point then
		return aRoleData.point > bRoleData.point
	end

	local aZhandouli = getSaveZhandouli(auuid)
	local bZhandouli = getSaveZhandouli(buuid)

	if aZhandouli ~= bZhandouli then
		return aZhandouli > bZhandouli
	end 
end

function sortJifenBoard()
	local rank2Uuid = getGodWarRank2Uuid()
	if not rank2Uuid then return end

	table.sort(rank2Uuid, cmpJiFenRank)

	updateGodWarRank(rank2Uuid)
end

--保存战斗记录
function addCombatRecord(cbParam,combatInfo,result)
	local atkUuid = cbParam.atkUuid
	local defUuid = cbParam.defUuid
	local atkRoleData = getGodWarDataByUuid(atkUuid)
	local defRoleData = getGodWarDataByUuid(defUuid)
	if JjcDB.isNpc(atkRoleData) then
		combatInfo.attacker = atkRoleData
	end
	if JjcDB.isNpc(defRoleData) then
		combatInfo.defender = defRoleData
	end

	local record = {}
	record.combatInfo = combatInfo
	record.result = result
	record.time = os.time()
	LuaMongo.insert(DB.db_jjcGodWar_record, record)

	return record._id
end

--排位赛刷新排行榜
function sortPaiWeiBoard(state)
	local paiweiMatch = getMatch2Fight(state)
	if not paiweiMatch then return end
	local winGroup = {}
	local loseGroup = {}
	for i=1,#paiweiMatch do
		local fenzuData = paiweiMatch[i]
		for j=1,#fenzuData do
			local pairsData = fenzuData[j]
			local atkUuid = pairsData.atkUuid
			local defUuid = pairsData.defUuid
			local winUuid = pairsData.winUuid
			winGroup[#winGroup+1] = winUuid

			local loseUuid = atkUuid
			if winUuid == atkUuid then
				loseUuid = defUuid
			end
			loseGroup[#loseGroup+1] = loseUuid
		end
	end
	--require("common.Util").printTable(winGroup)
	--require("common.Util").printTable(loseGroup)
	table.sort(winGroup, cmpJiFenRank)
	table.sort(loseGroup, cmpJiFenRank)
	-- require("common.Util").printTable(winGroup)
	-- require("common.Util").printTable(loseGroup)
	-- print("#winGroup,#loseGroup",#winGroup,#loseGroup)
	local rank2Uuid = getGodWarRank2Uuid()
	if not rank2Uuid then return end
	
	for i=1,#winGroup do
		rank2Uuid[i] = winGroup[i]
	end
	--print("#winGroup",#winGroup)
	local index = 0
	local finalRank = #loseGroup+#winGroup
	for i=#winGroup+1,finalRank do
		index = index + 1
		rank2Uuid[i] = loseGroup[index]
	end
	--require("common.Util").printTable(rank2Uuid)
	updateGodWarRank(rank2Uuid)
end

--获取参与的所有比赛,没有win就是还没开打
function getAllMatchByUuid(uuid)
	local match2Fight = getGodWarMatch2Fight()
	if not match2Fight then return end
	if #match2Fight < 1 then return end
	local myComBat = nil
	for state=1,#match2Fight do
		local stateData = match2Fight[state]
		if stateData then
			for fenzuID=1,#stateData do
				local fenzuData = stateData[fenzuID]
				for pairsIndex=1,#fenzuData do
					local pairsData = fenzuData[pairsIndex]
					local atkUuid = pairsData.atkUuid
					local defUuid = pairsData.defUuid
					if atkUuid == uuid or 
						defUuid == uuid then
						myComBat = myComBat or {}
						local index = #myComBat + 1
						myComBat[index] = {}
						myComBat[index].state = state
						myComBat[index].winUuid = pairsData.winUuid or ""
						myComBat[index].vestID = pairsData.vestID or ""
						myComBat[index].atkUuid = atkUuid
						myComBat[index].defUuid = defUuid
					end
				end
			end
		end
	end

	return myComBat
end

--获取战斗结果列表
function getCombatResultListByUuid(uuid)
	local roleData = getGodWarDataByUuid(uuid)
	if not roleData then return end

	return roleData.combatResultList
end

-- 根据记录id获取记录详情
function getRecord(vestID)
	if not vestID then return end
	QueryByVestID._id = vestID
	local record = {}
	LuaMongo.find(DB.db_jjcGodWar_record, QueryByVestID)    
	if not LuaMongo.next(record) then 
		return 
	end
    return record	
end

-- 保存当前战斗需要数据的镜像
function saveCombatData(godWarDB,state)
	if godWarDB.saveCombatState and godWarDB.saveCombatState == state then return end

	local rankMax = 128
	if state == JjcGodWarLogic.GODWAR_STATE_PAIWEI32 then
		rankMax = 32
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI16 then
		rankMax = 16
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI8 then
		rankMax = 8
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI4 then
		rankMax = 4
	elseif state == JjcGodWarLogic.GODWAR_STATE_PAIWEI1 then	
		rankMax = 2
	end

	local uuid2Roles = godWarDB.uuid2Roles
	local rank2Uuid = godWarDB.rank2Uuid

	if not uuid2Roles or not rank2Uuid then return end

	for rank=1,rankMax do
		local uuid = rank2Uuid[rank]
		local roleData = uuid2Roles[uuid]
		if not JjcDB.isNpc(roleData) then
			local fakeHuman = nil
			local db = RoleDBLogic.getDb(uuid)
			if db then
				fakeHuman = {}
				fakeHuman.db = db
				local objList, helpList, rolebase,formation = CombatLogic.getHumanObjList(fakeHuman, CombatDefine.COMBAT_TYPE4)
				roleData.objList = Util.copyTable(objList)
				roleData.helpList = Util.copyTable(helpList)
				roleData.rolebase = Util.copyTable(rolebase)
				roleData.formation = formation
				--require("common.Util").printTable(roleData)
			end
		end
	end

	updateGodWarRoleData(uuid2Roles)
	--require("common.Util").printTable(uuid2Roles)
	godWarDB.saveCombatState = state
end

--竞猜币 首轮默认60，第二轮开始，上一轮有竞猜接着送60
function getJingCaiBiCnt(human,state)
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return 0 end

	local uuid2Yazhu = getGodWarUuid2Yazhu()
	local yaData = nil

	if not uuid2Yazhu then
		local godWarDB = getGodWarDB()
		godWarDB.uuid2Yazhu = {}
		updateGodWarDB(godWarDB)
		uuid2Yazhu = godWarDB.uuid2Yazhu
	end

	if not uuid2Yazhu[human.db._id] then
		uuid2Yazhu[human.db._id] = {}
		uuid2Yazhu[human.db._id].jingCaiBi = JjcGodWarExcel.jingCai[1].jingCaiSongBi
		uuid2Yazhu[human.db._id].jingCai = nil
		updateGodWarYaZhu(uuid2Yazhu)
	end

	-- 如果 当前回合 没有押注 并且 竞猜币为0  送60 竞猜币
	if uuid2Yazhu[human.db._id].jingCaiBi <= 0 then
		yaData = getJingCaiYaZhu(human.db._id)
		if yaData and yaData[state] and yaData[state].yaUuid then			
		else
			uuid2Yazhu[human.db._id].jingCaiBi = JjcGodWarExcel.jingCai[1].jingCaiSongBi
		end
	end
	updateGodWarYaZhuByUuid(uuid2Yazhu[human.db._id],human.db._id)

	return uuid2Yazhu[human.db._id].jingCaiBi
end


--保存战报
function makeZhanBao(state)
	if state == JjcGodWarLogic.GODWAR_STATE_WAIT or state == JjcGodWarLogic.GODWAR_STATE_END then return end

	local data = getMatch2Fight(state)
	if not data then return end

	for i=1,#data do
		local fenzuData = data[i]
		for j=1,#fenzuData do
			local pairsData = fenzuData[j]
			local vestID = pairsData.vestID
			local atkUuid = pairsData.atkUuid
			local defUuid = pairsData.defUuid
			local winUuid = pairsData.winUuid
			if winUuid and vestID then
				local record = getRecord(vestID)
				if record then
					local combatInfo = record.combatInfo
					if combatInfo then 
						local atkRank = getRankByUuid(atkUuid)
				    	local defRank = getRankByUuid(defUuid)
				        WarReportLogic.add(WarReportLogic.WAR_REPORT_2, combatInfo, atkRank, defRank)
					end
				end
			end
		end
	end
end